package com.dingwen.treasure.business.component.bar;

import cn.hutool.json.JSONUtil;
import com.dingwen.treasure.base.enums.TaskType;
import com.dingwen.treasure.business.service.TestBarService;
import com.dingwen.treasure.common.redis.service.RedisService;
import com.dingwen.treasure.core.component.AbstractProgressBarTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * 测试进度条任务
 *
 * @author dingwen
 * @date 2022/12/08
 */
@Component("testProgressBarTask")
@Slf4j
public class TestProgressBarTask extends AbstractProgressBarTask<Boolean, Integer> {

    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolTaskExecutor asyncExecutor;

    @Resource
    private TestBarService testBarService;

    @Override
    protected RedisService getRedisService() {
        return redisService;
    }

    @Override
    protected ThreadPoolTaskExecutor getAsyncExecutor() {
        return asyncExecutor;
    }

    @Override
    protected List<Supplier<Boolean>> getTasks(Integer param) {
        // 任务信息原始数据
        List<Integer> taskOriginalData = testBarService.getTaskOriginalData(param);
        // 组装任务信息
        List<Supplier<Boolean>> suppliers = new ArrayList<>(taskOriginalData.size());
        taskOriginalData.stream().forEach(num ->suppliers.add(()-> testBarService.executeTask(param,num)));
        return suppliers;
    }

    @Override
    protected void after(String taskId, TaskType taskType, String taskKey, Integer param, List<Boolean> resultData) {
        log.info("多线程进度条任务执行收尾方法,任务id:{},任务类型:{},任务key:{},入参:{},返回值:{}",
                taskId,taskType.getCode(),
                taskKey,
                param,
                JSONUtil.toJsonPrettyStr(resultData)
        );
        testBarService.after();
        log.info("{}多线程进度条任务执行完成",taskKey);
    }
}
